import { message } from "ant-design-vue";
import { loginApi } from "@/api";
import { setToken } from "@/utils/cookie";
import mainStore from "@/stores/main";
import md5 from "md5";
import { cloneDeep } from "@/utils/lodash";
type LoginState = LoginParams;
export default function useLogin() {
    const loginState = reactive<LoginState>({
        username: "",
        password: ""
    });
    const $store = mainStore();
    const $router = useRouter();
    const loginLoading = ref(false);
    const handleFinish = () => {
        loginLoading.value = true;
        const obj = cloneDeep(loginState);
        obj.password = md5(obj.password);
        loginApi(obj)
            .then((res) => {
                if (res.data.code === 200) {
                    message.success("操作成功!");
                    // 过期时间
                    setToken(res.data.data.token);
                    $store.author = res.data.data.author;
                    $store.username = res.data.data.username;
                    $router.replace("/");
                } else if (res.data.code === 406) {
                    message.error(res.data.msg);
                } else {
                    message.error("登录失败!");
                }
            })
            .finally(() => {
                loginLoading.value = false;
            });
    };
    return {
        loginState,
        handleFinish,
        loginLoading
    };
}
